//
//  SheetManager.swift
//  Response
//
//  Created by JunMing on 2020/1/14.
//  Copyright © 2020 JMZhao. All rights reserved.
//

import UIKit

enum SheetDircation {
    case top,left,right,bottom,center,animation,buyVip,yinsi
}

class SheetItem {
    var title:String?
    var icon:UIImage?
    var topLogo:UIImage?
    var subTitle:String?
    var content:String?
    var attrStr:NSAttributedString?
    var eventName:String?
    var className:String!
    var models:[AlertItem]?
    var priority = 100
    var bkgColor = UIColor.black.withAlphaComponent(0.5)
    // 是否能透传点击消息
    var canPierce = false
    var sheetType = SheetDircation.center
    
    init(title:String) {
        self.title = title
    }
}

// MARK: -- 自定义展现 协议
protocol SheetCompProtocol {
    func remove(_ backView:SheetbackView)
    func updateView()
    var item: SheetItem? { get set }
}

extension SheetCompProtocol {
    func remove(_ backView:SheetbackView) {
        UIView.animate(withDuration: 0.3, animations: {
            backView.alpha = 0
        }) { _ in
            backView.removeFromSuperview()
        }
    }
}

class SheetManager {
    private var backView = SheetbackView()
    @discardableResult
    init(superView:UIView?,item:SheetItem) {
        if let view = superView {
            backView.frame = view.bounds
            view.addSubview(backView)
            backView.snp.makeConstraints { (make) in
                make.edges.equalTo(view)
            }
        }else {
            guard let window = UIApplication.shared.keyWindow else { return }
            backView.frame = window.bounds
            window.addSubview(backView)
            backView.snp.makeConstraints { (make) in
                make.edges.equalTo(window)
            }
        }
        backView.container = initContainer(item: item)
        backView.container.item = item
        backView.backgroundColor = item.bkgColor
        backView.addSubview(backView.container as! UIView)
    }
    
    private func initContainer(item:SheetItem) -> SheetCompProtocol? {
        func classFromString(name: String) -> SheetCompProtocol? {
            if let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String? {
                let classStringName = appName + "." + name
                guard let newClass = NSClassFromString(classStringName) as? UIView.Type else {
                    return nil
                }
                return (newClass.init() as! SheetCompProtocol)
            }
            return nil;
        }
        return classFromString(name: item.className)
    }
    
    public func resetItem(item:SheetItem) {
        backView.container.item = item
    }
    
    public func update() {
        DispatchQueue.main.async {
            self.backView.updateBackView()
            self.backView.container.updateView()
        }
    }
    
    public func hide() {
        DispatchQueue.main.async {
            self.backView.container.remove(self.backView)
        }
    }
}

// MARK: -- 背景View
class SheetbackView: UIView {
    var container:SheetCompProtocol!
    var close = UIButton(type: .system)
    override init(frame: CGRect) {
        super.init(frame: frame)
        close.setBackgroundImage(UIImage(named: "关闭"), for: .normal)
        close.tintColor = UIColor.white
        close.addTarget(self, action: #selector(closeAction), for: .touchUpInside)
        addSubview(close)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        if !container.item!.canPierce {
            return super.hitTest(point, with: event)
        }
        
        if isHidden || alpha < 0.01 || isUserInteractionEnabled {
            return nil
        }
        
        let view = super.hitTest(point, with: event)
        if (view?.isEqual(self))! {
            return nil
        }else {
            return view
        }
    }
    
    @objc func closeAction() {
        container.remove(self)
    }
    
    func updateBackView() {
        let contain = container as! UIView
        switch container.item?.sheetType {
        case .top?:
            // BookTopAlert
            contain.snp.makeConstraints { (make) in
                make.centerX.equalTo(snp.centerX)
                make.left.equalTo(snp.left).offset(30)
                make.right.equalTo(snp.right).offset(-30)
                make.height.equalTo(39)
                if #available(iOS 11.0, *) {
                    make.top.equalTo(safeAreaLayoutGuide.snp.top).offset(5)
                }else{
                    make.top.equalTo(snp_top).offset(10)
                }
            }
        case .left?:
            print("top")
        case .right?:
            // BookInfoAlert
            contain.snp.makeConstraints { (make) in
                make.center.equalTo(snp.center)
                make.height.equalTo(160)
                make.width.equalTo(290)
            }
        case .bottom?:
            guard let coun = container.item?.models?.count else { return }
            let count = (coun+1)*(44+1)+5 + (Tools.getVip() ? 0:20)
            contain.snp.remakeConstraints { (make) in
                make.width.equalTo(self)
                make.height.equalTo(count)
                if #available(iOS 11.0, *) {
                    make.bottom.equalTo(safeAreaLayoutGuide.snp.bottom)
                }else{
                    make.bottom.equalTo(snp_bottom)
                }
            }
        case .center?:
            contain.snp.makeConstraints { (make) in
                make.center.equalTo(snp.center)
                make.height.equalTo(370)
                make.width.equalTo(270)
            }
            close.snp.makeConstraints { (make) in
                make.top.equalTo(contain.snp.bottom).offset(20)
                make.centerX.equalTo(contain)
                make.height.width.equalTo(34)
            }
            
        case .animation?:
            contain.snp.makeConstraints { (make) in
                make.center.equalTo(snp.center)
                make.height.width.equalTo(60)
            }
            
            close.snp.makeConstraints { (make) in
                make.top.equalTo(contain.snp.bottom).offset(20)
                make.centerX.equalTo(contain)
                make.height.width.equalTo(34)
            }
        // BookYinSiAlert
        case .yinsi?:
            contain.snp.makeConstraints { (make) in
                make.center.equalTo(snp.center)
                make.width.equalTo(260)
                make.height.equalTo(200)
            }
        case .buyVip?:
            contain.snp.remakeConstraints { (make) in
                make.width.equalTo(self)
                make.height.equalTo(500)
                if #available(iOS 11.0, *) {
                    make.bottom.equalTo(safeAreaLayoutGuide.snp.bottom)
                }else{
                    make.bottom.equalTo(snp.bottom)
                }
            }
        default:
            print("top")
        }
    }
}
